<template>
  <view class="analysis-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">数据分析中心</view>
      <view class="subtitle">实时掌握图书市场动态</view>
    </view>
    
    <!-- 过滤器区域 -->
    <view class="filter-container">
      <view class="filter-label">时间范围：</view>
      <view class="filter-options">
        <view 
          v-for="(item, index) in timeRangeOptions" 
          :key="index"
          :class="['option-item', analysisStore.filter.timeRange === item.value ? 'active' : '']"
          @click="changeTimeRange(item.value)"
        >{{item.label}}</view>
      </view>
      
      <view class="filter-label">分类筛选：</view>
      <view class="filter-selector">
        <picker 
          mode="selector" 
          :range="categoryOptions" 
          range-key="name"
          @change="changeCategoryId"
        >
          <view class="selector-content">
            <text>{{getCategoryName()}}</text>
            <text class="iconfont icon-down"></text>
          </view>
        </picker>
      </view>
    </view>
    
    <!-- 主要功能卡片 -->
    <view class="cards-container">
      <!-- 销量排行卡片 -->
      <view class="analysis-card" @click="navigateTo('sales-ranking')">
        <image class="card-icon" src="/static/analysis/sales-icon.png" mode="aspectFit"></image>
        <view class="card-info">
          <view class="card-title">销量排行</view>
          <view class="card-desc">查看各类图书热销排行榜</view>
        </view>
        <text class="iconfont icon-right"></text>
      </view>
      
      <!-- 评分分布卡片 -->
      <view class="analysis-card" @click="navigateTo('rating-distribution')">
        <image class="card-icon" src="/static/analysis/rating-icon.png" mode="aspectFit"></image>
        <view class="card-info">
          <view class="card-title">评分分布</view>
          <view class="card-desc">了解用户评分情况及分布</view>
        </view>
        <text class="iconfont icon-right"></text>
      </view>
      
      <!-- 热门关键词卡片 -->
      <view class="analysis-card" @click="navigateTo('hot-keywords')">
        <image class="card-icon" src="/static/analysis/keyword-icon.png" mode="aspectFit"></image>
        <view class="card-info">
          <view class="card-title">热门关键词</view>
          <view class="card-desc">发现热门搜索关键词趋势</view>
        </view>
        <text class="iconfont icon-right"></text>
      </view>
      
      <!-- 市场趋势卡片 -->
      <view class="analysis-card" @click="navigateTo('market-trend')">
        <image class="card-icon" src="/static/analysis/trend-icon.png" mode="aspectFit"></image>
        <view class="card-info">
          <view class="card-title">市场趋势</view>
          <view class="card-desc">掌握图书市场销售动态</view>
        </view>
        <text class="iconfont icon-right"></text>
      </view>
    </view>
    
    <!-- 数据概览区域 -->
    <view class="overview-container">
      <view class="section-title">
        <text>数据概览</text>
        <text class="title-desc">{{analysisStore.timeRangeText}}数据</text>
      </view>
      
      <view class="overview-cards">
        <view class="overview-card">
          <view class="card-value">{{topSalesCount}}</view>
          <view class="card-label">热销图书销量</view>
        </view>
        <view class="overview-card">
          <view class="card-value">{{avgRating}}</view>
          <view class="card-label">平均评分</view>
        </view>
        <view class="overview-card">
          <view class="card-value">{{keywordCount}}</view>
          <view class="card-label">热门关键词数</view>
        </view>
      </view>
    </view>
    
    <!-- 底部提示 -->
    <view class="footer-tip">
      <text>点击卡片查看详细分析数据</text>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue';
import { useAnalysisStore } from '@/store/analysis.js';
import { useBookStore } from '@/store/book.js';

export default {
  name: 'DataAnalysisIndex',
  setup() {
    // 获取分析数据仓库
    const analysisStore = useAnalysisStore();
    // 获取图书仓库，用于获取分类数据
    const bookStore = useBookStore();
    
    // 页面数据初始化
    const timeRangeOptions = [
      { label: '本周', value: 'week' },
      { label: '本月', value: 'month' },
      { label: '本年', value: 'year' },
      { label: '全部', value: 'all' }
    ];
    
    // 分类选项数据
    const categoryOptions = ref([
      { id: 0, name: '全部分类' }
    ]);
    
    // 概览数据
    const topSalesCount = ref('--');
    const avgRating = ref('--');
    const keywordCount = ref('--');
    
    // 初始化页面
    onMounted(async () => {
      // 加载分类数据
      await loadCategories();
      
      // 加载概览数据
      loadOverviewData();
    });
    
    // 加载分类数据
    async function loadCategories() {
      try {
        await bookStore.fetchCategories();
        // 添加分类选项
        if (bookStore.categories && bookStore.categories.length > 0) {
          categoryOptions.value = [
            { id: 0, name: '全部分类' },
            ...bookStore.categories
          ];
        }
      } catch (error) {
        console.error('加载分类数据失败：', error);
      }
    }
    
    // 加载概览数据
    async function loadOverviewData() {
      try {
        // 加载销量排行数据，用于获取热销书籍销量
        const salesData = await analysisStore.fetchSalesRanking();
        if (salesData && salesData.length > 0) {
          // 获取销量最高的书籍销量
          topSalesCount.value = salesData[0].salesCount;
        }
        
        // 加载评分分布数据，用于计算平均评分
        const ratingData = await analysisStore.fetchRatingDistribution();
        if (ratingData && ratingData.length > 0) {
          // 计算加权平均分
          let totalScore = 0;
          let totalCount = 0;
          ratingData.forEach(item => {
            totalScore += item.rating * item.count;
            totalCount += item.count;
          });
          avgRating.value = totalCount > 0 ? (totalScore / totalCount).toFixed(1) : '--';
        }
        
        // 加载热门关键词数据
        const keywordData = await analysisStore.fetchHotKeywords();
        if (keywordData && keywordData.length > 0) {
          keywordCount.value = keywordData.length;
        }
      } catch (error) {
        console.error('加载概览数据失败：', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      }
    }
    
    // 切换时间范围
    function changeTimeRange(timeRange) {
      analysisStore.setFilter({ timeRange });
      loadOverviewData();
    }
    
    // 切换分类
    function changeCategoryId(e) {
      const index = e.detail.value;
      const categoryId = categoryOptions.value[index].id;
      analysisStore.setFilter({ categoryId });
      loadOverviewData();
    }
    
    // 获取当前选中的分类名称
    function getCategoryName() {
      const category = categoryOptions.value.find(item => item.id === analysisStore.filter.categoryId);
      return category ? category.name : '全部分类';
    }
    
    // 页面导航
    function navigateTo(page) {
      uni.navigateTo({
        url: `/pages/data-analysis/${page}/${page}`
      });
    }
    
    return {
      analysisStore,
      timeRangeOptions,
      categoryOptions,
      topSalesCount,
      avgRating,
      keywordCount,
      changeTimeRange,
      changeCategoryId,
      getCategoryName,
      navigateTo
    };
  }
};
</script>

<style lang="scss">
.analysis-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  
  /* 顶部标题样式 */
  .header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }
  }
  
  /* 过滤器区域样式 */
  .filter-container {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .filter-label {
      font-size: 26rpx;
      color: #666666;
      margin-bottom: 10rpx;
    }
    
    .filter-options {
      display: flex;
      margin-bottom: 20rpx;
      
      .option-item {
        font-size: 24rpx;
        color: #666666;
        background-color: #f5f5f5;
        padding: 10rpx 20rpx;
        border-radius: 30rpx;
        margin-right: 20rpx;
        transition: all 0.3s;
        
        &.active {
          color: #ffffff;
          background-color: #0066ff;
        }
      }
    }
    
    .filter-selector {
      margin-bottom: 10rpx;
      
      .selector-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f5f5f5;
        padding: 15rpx 20rpx;
        border-radius: 10rpx;
        font-size: 26rpx;
        color: #333333;
        
        .iconfont {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }
  
  /* 功能卡片样式 */
  .cards-container {
    margin-bottom: 30rpx;
    
    .analysis-card {
      display: flex;
      align-items: center;
      background-color: #ffffff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      
      .card-icon {
        width: 80rpx;
        height: 80rpx;
        margin-right: 20rpx;
        flex-shrink: 0;
      }
      
      .card-info {
        flex: 1;
        
        .card-title {
          font-size: 30rpx;
          font-weight: 500;
          color: #333333;
        }
        
        .card-desc {
          font-size: 24rpx;
          color: #999999;
          margin-top: 6rpx;
        }
      }
      
      .iconfont {
        font-size: 32rpx;
        color: #cccccc;
      }
    }
  }
  
  /* 数据概览区域样式 */
  .overview-container {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .section-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      
      .title-desc {
        font-size: 24rpx;
        font-weight: normal;
        color: #999999;
      }
    }
    
    .overview-cards {
      display: flex;
      justify-content: space-between;
      
      .overview-card {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        
        .card-value {
          font-size: 40rpx;
          color: #0066ff;
          font-weight: bold;
        }
        
        .card-label {
          font-size: 24rpx;
          color: #999999;
          margin-top: 10rpx;
        }
      }
    }
  }
  
  /* 底部提示样式 */
  .footer-tip {
    text-align: center;
    font-size: 24rpx;
    color: #999999;
    margin: 20rpx 0;
  }
}
</style>
